import { create } from "zustand";
import type { SysUserItem, SysUserLoginReq } from "@/services";
import { sysUserLogin, getSysUserInfo } from "@/services";
import { REFRESH_TOKEN, TOKEN } from "@/constants";

type State = {
  userInfo: SysUserItem;
};

type Actions = {
  getUserInfo: () => Promise<void>;
  userLoginIn: (loginIn: SysUserLoginReq) => Promise<boolean>;
  userLogout: () => void;
};

export const useUserStore = create<State & Actions>((set) => ({
  userInfo: {} as SysUserItem,
  getUserInfo: async () => {
    const res = await getSysUserInfo();
    if (res.code == 200) {
      const userInfo = res.data;
      set(() => ({ userInfo }));
    }
  },
  userLoginIn: async (loginIn: SysUserLoginReq) => {
    // 密码加密
    const res = await sysUserLogin(loginIn).catch((err) => {
      return undefined;
    });
    if (res?.code == 200) {
      localStorage.setItem(TOKEN, res.data.token);
      localStorage.setItem(REFRESH_TOKEN, res.data.refreshToken);
      return true;
    }
    return false;
  },
  userLogout: () => {
    localStorage.removeItem(TOKEN);
    localStorage.removeItem(REFRESH_TOKEN);
  },
}));
